package com.qd.p2p.web.action;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.adapted.AdaptedServiceFactory;
import com.qdlc.p2p.biz.adapted.AdaptedWithdrawService;
import com.qdlc.p2p.biz.service.AccountCashService;
import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.biz.util.NotifyRequestUrl;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.core.ReturnResult;
import com.qdlc.p2p.common.exception.AccountException;
import com.qdlc.p2p.common.util.MessageUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.common.util.ip.IPUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.Account;
import com.qdlc.p2p.dal.dto.AccountCash;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.AccountCashModel;
import com.qdlc.p2p.dal.util.UserTypeUtils;

/**
 * 提现
 * @author linya 2016-04-12
 */
public class CashAction extends BaseAction<AccountCashModel> implements ModelDriven<AccountCashModel> {
	
	@Resource
	private AccountService accountService;
	@Resource
	private AccountCashService accountCashService;
	
	AdaptedWithdrawService withdrawService = AdaptedServiceFactory.getService(AdaptedWithdrawService.class);

	/**
	 * [提现] 前往提现页面
	 * @author linya
	 */
	@Action(value="/member/cash/newCash",results = { @Result(name = "newCash", type = "ftl", location = "/member/cash/newCash.html"),
			@Result(name = "newCash_firm", type = "ftl", location = "/member_borrow/cash/newCash.html")})
	public String newCash() throws Exception {
		// 添加token
		saveToken("newCash");
		// 获取用户
		User user = getSessionUser();
		// 获取页面属性
		ReturnResult result = withdrawService.gotoNewCash(user);
		// 设置页面属性
		for(Map.Entry<String, Object> entry: result.getExtra().entrySet()){
			request.setAttribute(entry.getKey(), entry.getValue());
		}
		//设置跳转页面
		if (UserTypeUtils.isBorrowOrInverstment(user.getUserId())) {
			return "newCash_firm";
		} 
		return "newCash";
	}
	
	/**
	 * [提取]提现申请
	 * @return
	 * @author linya
	 */ 
	@SuppressWarnings("unchecked")
	@Action(value = "/member/cash/doCash",results = {
			@Result(name = "success", type = "ftl", location = "/member/account/newcash.html"),
			@Result(name = "result", type = "ftl", location = "/member/tpp/"+Constant.TPP_PACKAGE+"/cash.html"),
			@Result(name = "retResult", type = "ftl", location = "/retresult.html")}
	)
	public String doCash() throws Exception {
		
		// 获取当前用户信息
		User user = getSessionUser();
		
		// 获取提取请求参数
		double money = paramDouble("money");	// 提取金额
		String bankNo = paramString("bankNo");	// 提取银行卡
		String payPwd = paramString("payPwd");	// 交易密码
		
		// 检测提取前置条件
		ReturnResult result = withdrawService.doCashPreCondition(user, money, bankNo, payPwd);
		if(result.isError()){
			throw new AccountException(result.getErrorInfo(), "/member/cash/newCash.html");
		}
		
		// 检测Token
		checkToken("newCash", "/member/cash/newCash");
		
		// 提现
		String ip = IPUtil.getRemoteIP(request);
		result = withdrawService.doWithdraw(user, bankNo, money, ip);
		if(result.isError()){
			throw new AccountException(result.getErrorInfo(), "/member/cash/newCash.html");
		}

		// 提现后返回
		String resultFlag = System.currentTimeMillis() + "" + Math.random() * 10000;
		request.setAttribute("resultFlag", resultFlag);
		request.setAttribute("left_url", "/member/cash/newCash.html");
		request.setAttribute("right_url", "/member/cash/log.html");
		request.setAttribute("back_url", "/member/cash/newCash.html");
		request.setAttribute("left_msg", MessageUtil.getMessage("MS104003002"));
		request.setAttribute("right_msg", MessageUtil.getMessage("MS104003001"));
		request.setAttribute("r_msg", "平台已受理，请等待！");
		Global.TASK_RESULT_MAP.put(resultFlag, "success");
		
		return "retResult";
	}
	
    /**
     * [新浪][提取] 提取异步回调
     * @throws Exception
     */
    @Action(value = NotifyRequestUrl.ACTION_WITH_DRAW_URL)
    public void tppCashNotice() throws Exception {
    	
    	ReturnResult result = withdrawService.notifying(request);
        
    	response.setContentType("text/html;charset=UTF-8");
        if(result.isSuccess()){
        	response.getWriter().print("success");
        }else{
        	response.getWriter().print(result.getErrorInfo());
        }
    }
	
		
	/**
	 * 取消提现
	 * 
	 * @return
	 */
	@Action("/member/cash/cancel")
	public void cancel() throws Exception {
		redirect("/member/cash/log.html");
	}

	/**
	 * 提现记录
	 * 
	 * @return
	 */
	@Action(value="/member/cash/log",results = { @Result(name = "log", type = "ftl", location = "/member/cash/log.html"),
			@Result(name = "log_firm", type = "ftl", location = "/member_borrow/cash/log.html")})
	public String log() throws Exception {
		User user = getSessionUser();
		long userId = user.getUserId();
		Account account = accountService.findAccountByUserId(userId);
		request.setAttribute("account", account);
		if (UserTypeUtils.isBorrowOrInverstment(user.getUserId())) {
			return "log_firm";
		} 
		return "log";
	}

	
	/**
	 * 获取提现记录列表
	 * @throws Exception
	 */
	@Action("/member/cash/logList")
	public void logList() throws Exception {
		User user = getSessionUser();
		long userId = user.getUserId();
		String status = paramString("status");
		if(StringUtil.isBlank(status)){
			model.setStatus(99);
		}
		PageDataList<AccountCashModel> pageDateList = accountCashService.list(userId, model.getPage(),model);
		AccountCash model = accountCashService.getCashMessage(userId);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("data", pageDateList);
		data.put("model", model);
		printWebJson(getStringOfJpaObj(data));
	}

}
